package com.rn.gypsophila.grpc;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.rn.gypsophila.grpc.CalculateServiceImpl.condition;
import static com.rn.gypsophila.grpc.CalculateServiceImpl.LOCK;

@Slf4j
public class GrpcServer {
    private static final int DEFAULT_PORT = 50051;
    private int port;
    private Server server;

    public GrpcServer(int port) {
        this(port, ServerBuilder.forPort(port));
    }

    public GrpcServer(int port, ServerBuilder<?> serverBuilder) {
        this.port = port;
        server = serverBuilder.addService(new CalculateServiceImpl()).build();
    }

    private void start() throws IOException {
        server.start();
        log.info("Server has started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread(GrpcServer.this::stop));
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    private void imitate() {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
        executorService.scheduleWithFixedDelay(() -> {
            LOCK.lock();
            try {
                log.info("测试线程:" + Thread.currentThread().getName() + "获得锁");
                condition.signalAll();
            } finally {
                LOCK.unlock();
            }
        }, 3, 3, TimeUnit.SECONDS);
    }

    public static void main(String[] args) {
        GrpcServer server = new GrpcServer(DEFAULT_PORT);
        try {
            server.start();
            server.imitate();
            server.blockUntilShutdown();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}
